package com.zues.thread.method.interrupt;


import com.zues.thread.util.ThreadUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.LockSupport;

/**
 * 打断方法测试 interrupt
 * 打断sleep、wait、join的线程,这几个方法会让线程进入阻塞状态
 * 打断sleep的线程，会清空打断状态，以sleep为例
 *
 */
@Slf4j(topic = "c.InterruptTest")
public class InterruptTest {

    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(() -> {
            ThreadUtil.sleep(1);
        },"t1");
        t1.start();
        Thread.sleep(500);
        //打断正在sleep的线程会报错：java.lang.InterruptedException，会清空打断状态
        t1.interrupt();
        log.debug("打断状态：{}", t1.isInterrupted());

        test1();
        test2();
    }

    /**
     * 打断正在循环的线程，打断状态不会被清除
     * @throws InterruptedException
     */
    private static void test1() throws InterruptedException {
        Thread t2 = new Thread(() -> {
            while (true){
                Thread currentThread = Thread.currentThread();
                boolean interrupted = currentThread.isInterrupted();
                if (interrupted) {
                    log.debug("打断状态：{}", interrupted);
                    break;
                }
            }
        }, "t2");
        t2.start();
        Thread.sleep(500);
        t2.interrupt();
    }

    /**
     * 打断park线程，不会清除打断状态
     * @throws InterruptedException
     */
    private static void test2() throws InterruptedException {
        Thread t3 = new Thread(() -> {
            log.debug("park...");
            LockSupport.park();
            log.debug("unpark...");
            log.debug("打断状态：{}", Thread.currentThread().isInterrupted());
        }, "t3");
        t3.start();
        Thread.sleep(500);
        t3.interrupt();
    }
}
